export const KEY = 'goodsdata';
export var  valueObj = {goodsId:0,count:0};

export function setItem(value) {
	var jsonString = localStorage.getItem(KEY);
	var jsonString = jsonString ||'[]';
	var arr = JSON.parse(jsonString);
	arr.push(value);
	localStorage.setItem(KEY,JSON.stringify(arr));	
}

export function getItem(){
	var jsonString = localStorage.getItem(KEY);
	jsonString = jsonString || '[]';
	return JSON.parse(jsonString);
}

export function getgoodsObject(){
	var arr = getItem();
	var resObj={};
	for(var i=0;i<arr.length;i++){
		var item = arr[i];
		if (!resObj[item.goodsId]) {
			resObj[item.goodsId]=item.count;	
		}else{
			var count = resObj[item.goodsId];
			resObj[item.goodsId] = count+item.count;
		}		
	}
	return resObj;
}

export function updateData(obj){
	var arr = getItem();

	var count=1;
	if (obj.type == 'add') {
		arr.push({goodsId:obj.goodsId,count:count})
	}else{
		for (var i = 0; i < arr.length; i++) {
			//如果获取到的count是1，则删除该id
			if (arr[i].goodsId == obj.goodsId) {
				if (arr[i].count>1) {
					arr[i].count = arr[i].count-1;
					break;	
				}else{
					arr.splice(i,1);
					break;
				}
			}
		}
	}
	localStorage.setItem(KEY,JSON.stringify(arr));	
}

export function removeItem(goodsId){
	var arr = getItem();
	for (var i = arr.length-1; i >= 0; i--) {
		if(arr[i].goodsId==goodsId){
			arr.splice(i,1);
		}
	}
	localStorage.setItem(KEY,JSON.stringify(arr));	

}